package com.kitty.game.equip.handler;

import com.kitty.game.attribute.config.Attribute;
import com.kitty.game.bag.message.RespFlushPack;
import com.kitty.game.bag.message.RespIconCartoon;
import com.kitty.game.enter.FiedValue;
import com.kitty.game.equip.handler.UpgradeHandler;
import com.kitty.game.equip.model.RoleEquip;
import com.kitty.game.equip.model.RoleEquipField;
import com.kitty.game.role.model.Role;
import com.kitty.mina.message.MessagePusher;
import org.springframework.stereotype.Component;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Random;

import static com.kitty.game.utils.Const.MONEY_NAME;
import static com.kitty.game.utils.Const.ROLE_RESOURCE_NOT_ENOUGH;

/**
 * 装备拆分
 */
@Component("EquipSplit")
public class EquipSplitHandler extends UpgradeHandler {
    /**
     * 没有属性可以拆分
     */
    private static final String NO_FIELD_SPLIT = "很抱歉，#R{0}#n没有属性可拆分了。";
    private static final String FAIL = "真遗憾，属性拆分未成功。";
    private static final String SUCCESS = "你成功拆分出了属性#R{0}#n。";

    private static final String HUNDUNYU = "混沌玉";
    private static final String NO_LIMIT = "0";
    private static final String LIMIT = "1";
    private static final String NO_LIMIT_USEHUNDUNYU = "2";
    private static final String LIMIT_USEHUNDUNYU = "3";


    /**
     * 拆分一条装备上随机的属性
     */
    private RoleEquipField splitEquip(RoleEquip roleEquip, Role role) {
        return getFiedValue(roleEquip, role);
    }

    @Override
    public String acceptUpgrade(Role role, int upgradePos, String param) {
        RoleEquip roleEquip = equipService.getRoleEquipByPos(role, upgradePos);
        if(roleEquip==null){
            return "请放入正确的装备。";
        }
        if (!isRightPosition(roleEquip.queryEquipPos(false))) {
            return MessageFormat.format(NO_RIGHT_POSITION, "拆分", roleEquip.getName());
        }

        String noEnough = checkResource(role, param, roleEquip.queryLevel());
        if (noEnough != null) {
            return noEnough;
        }

        short newPos = getVacancy(role);
        if (newPos <= 0) {
            return ROLE_VACANCY_NOT_ENOUGH;
        }

        return doUpgrade(role, roleEquip, newPos, param);

    }

    @Override
    public String checkResource(Object... objects) {
        /**拆分装备需要黑水晶 混沌玉 根据打造的选项*/
        Role role = (Role) objects[0];
        String opType = (String) objects[1];
        short level = (short) objects[2];
        if (level >= 70) {
            if (role.getMoney() < needCash(level,0)) {
                return MessageFormat.format(ROLE_RESOURCE_NOT_ENOUGH, MONEY_NAME);
            }
        }
        /**限制黑水晶*/
        int limitHeiShui = equipService.getCount(HEISHUIJING, true, role);
        /**不限制黑水晶*/
        int noLimitheiShui = equipService.getCount(HEISHUIJING, false, role);
        /**限制混沌玉*/
        int limitYu = equipService.getCount(HUNDUNYU, true, role);
        /**不限制混沌玉*/
        int noLimitYu = equipService.getCount(HUNDUNYU, false, role);
        /**判断需要的资源是否足够*/
        switch (opType) {
            case NO_LIMIT:
                if (noLimitheiShui <= 0) {
                    return MessageFormat.format(ROLE_RESOURCE_NOT_ENOUGH, HEISHUIJING);
                }
                break;
            case LIMIT:
                if (limitHeiShui <= 0) {
                    return MessageFormat.format(ROLE_RESOURCE_NOT_ENOUGH, HEISHUIJING);
                }
                break;
            case NO_LIMIT_USEHUNDUNYU:
                if (noLimitheiShui <= 0) {
                    return MessageFormat.format(ROLE_RESOURCE_NOT_ENOUGH, HEISHUIJING);
                }
                if (noLimitYu <= 0) {
                    return MessageFormat.format(ROLE_RESOURCE_NOT_ENOUGH, HUNDUNYU);
                }
                break;
            case LIMIT_USEHUNDUNYU:
                if (limitHeiShui <= 0) {
                    return MessageFormat.format(ROLE_RESOURCE_NOT_ENOUGH, HEISHUIJING);
                }
                if (limitYu <= 0) {
                    return MessageFormat.format(ROLE_RESOURCE_NOT_ENOUGH, HUNDUNYU);
                }
                break;
            default:
                return ERROR_OPTYPE;
        }

        return null;
    }


    @Override
    public int needCash(short level,int pos) {
        return level >= 70 ? level * 700 + 3000 : 0;
    }


    @Override
    public String doUpgrade(Role role, Object... params) {

        RoleEquip roleEquip = (RoleEquip) params[0];
        short newPos = (short) params[1];
        String opType = (String) params[2];

        /**扣钱*/
        roleService.subtractMoney(role, needCash(roleEquip.queryLevel(),0));

        /**随机一个成功的几率*/
        boolean success = new Random().nextBoolean();
        /**获得的属性黑水晶*/
        RoleEquip heiShuiJin = null;
        /**使用混沌玉 必定成功*/
        int limitItemNum = 0;
        /**获得的黑水晶是不是限制的*/
        boolean isNoLimit = false;

        switch (opType) {
            case NO_LIMIT:
                isNoLimit = true;
                equipService.delRoloEquip(HEISHUIJING, 1, false, role);
                break;
            case LIMIT:
                limitItemNum += equipService.delRoloEquip(HEISHUIJING, 1, true, role);
                break;
            case NO_LIMIT_USEHUNDUNYU:
                isNoLimit = true;
                success = UPGRADE_SUCCESS;
                equipService.delRoloEquip(HUNDUNYU, 1, false, role);
                equipService.delRoloEquip(HEISHUIJING, 1, false, role);
                break;
            case LIMIT_USEHUNDUNYU:
                success = UPGRADE_SUCCESS;
                limitItemNum += equipService.delRoloEquip(HUNDUNYU, 1, true, role);
                limitItemNum += equipService.delRoloEquip(HEISHUIJING, 1, true, role);
                break;
        }

        /**是否获得不显示的黑水晶*/
        if (limitItemNum == 0) {
            isNoLimit = true;
        }


        /**成功*/
        if (success) {
            RoleEquipField roleEquipField = splitEquip(roleEquip, role);
            if (roleEquipField == null) {
                return MessageFormat.format(NO_FIELD_SPLIT, roleEquip.getName());
            }
            roleEquipField.setType((short) 514);
            short type = 0;
            for (Map.Entry<Short, FiedValue> entry : roleEquipField.getField().entrySet()) {
                type = entry.getKey();
            }
            Attribute attribute = attrService.getAttr(type);
            // 黑水晶得到一条属性

            heiShuiJin = equipService.getBlackCrystal(role, isNoLimit, roleEquipField, limitItemNum, newPos);

            if (heiShuiJin == null) {
                return FAIL;
            }

            FiedValue fiedValue = heiShuiJin.getFields().get((short) 1).getField().get((short) 1);
            if (fiedValue != null) {
                fiedValue.setValue(fiedValue.getValue() + "·" + attribute.getValuename());
                heiShuiJin.setName((String) fiedValue.getValue());
            }
            fiedValue = heiShuiJin.getFields().get((short) 1).getField().get((short) 248);
            if (fiedValue != null) {
                fiedValue.setValue(roleEquip.queryEquipPos(false));// 黑水晶的部位
            }
            heiShuiJin.alterLevel(roleEquip.queryLevel());

            /**添加装备*/
            equipService.add(role, heiShuiJin);

            RespFlushPack respFlushPack = new RespFlushPack();
            respFlushPack.setType("bag");
            MessagePusher.pushMessage(role, respFlushPack);

            equipService.refreshRoleEquip(role,heiShuiJin);

            //获得动画
            RespIconCartoon respIconCartoon = new RespIconCartoon();
            respIconCartoon.setName(heiShuiJin.getName());
            respIconCartoon.setParam(heiShuiJin.getId() + "");
            MessagePusher.pushMessage(role, respIconCartoon);

            pushOperateResult(role,UPGRADE_SUCCESS);
            roleService.addAchieveScore(role,"301029");
            return MessageFormat.format(SUCCESS,attribute.getValuename());
        } else {
            roleService.addAchieveScore(role,"301018");
            pushOperateResult(role,UPGRADE_FAIL);
            return FAIL;
        }
    }


    @Override
    public String getUpdateTypeStr() {
        return "equip_split";
    }



    /**
     * 随机获得装备上的一条属性
     */
    private RoleEquipField getFiedValue(RoleEquip roleEquip, Role role) {
        Random random = new Random();
        ArrayList<FiedValue> arrayList = new ArrayList<>();
        for (Map.Entry<Short, RoleEquipField> entry : roleEquip.getFields().entrySet()) {
            if (entry.getValue().getType() != 514 && entry.getValue().getType() != 770 && entry.getValue().getType() != 1026) {
                continue;
            }
            if (entry.getValue().getField() == null) {
                continue;
            }
            for (Map.Entry<Short, FiedValue> entry1 : entry.getValue().getField().entrySet()) {
                arrayList.add(entry1.getValue());
            }
        }
        if (arrayList.size() == 0) {
            return null;
        }
        int index = random.nextInt(arrayList.size());
        FiedValue resultValue = arrayList.get(index);
        // 删掉原装备的属性
        short type = 0;
        out:
        for (Map.Entry<Short, RoleEquipField> entry : roleEquip.getFields().entrySet()) {
            if (entry.getValue().getType() != 514 && entry.getValue().getType() != 770 && entry.getValue().getType() != 1026) {
                continue;
            }
            if (entry.getValue().getField() == null) {
                continue;
            }
            for (Map.Entry<Short, FiedValue> entry1 : entry.getValue().getField().entrySet()) {
                if (entry1.getValue().getType() == resultValue.getType()) {
                    type = entry.getKey();
                    break out;
                }
            }
        }
        roleEquip.getFields().get(type).getField().remove(resultValue.getType());
        if (roleEquip.getFields().get(type).getField().size() <= 0) {
            roleEquip.getFields().remove(type);
        }

        //还有属性 更新装备
        boolean isdel = true;
        for (Map.Entry<Short, RoleEquipField> entry : roleEquip.getFields().entrySet()) {
            if (entry.getValue().getType() == 514 || entry.getValue().getType() == 770 || entry.getValue().getType() == 1026) {
                isdel = false;
                break;
            }
        }
        if (isdel) {
            //装备属性为空删除
            equipService.delRoleEquip(roleEquip, role);
        } else {
            refreshRoleEquip(role,roleEquip);
        }


        RoleEquipField roleEquipField = new RoleEquipField();
        roleEquipField.setType( type);
        roleEquipField.setField(new LinkedHashMap<>());
        roleEquipField.getField().put(resultValue.getType(), resultValue);
        return roleEquipField;
    }

}
